package com.lxm.controller;


import com.baomidou.mybatisplus.extension.api.R;
import com.lxm.entity.Admin;
import com.lxm.entity.Resource;
import com.lxm.entity.ResultEntity;
import com.lxm.service.IAdminRoleService;
import com.lxm.service.IResourceService;
import com.lxm.service.impl.ResourceServiceImpl;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 菜单管理 前端控制器
 * </p>
 *
 * @author lxm
 * @since 2021-11-18
 */
@RestController
@RequestMapping("/resource")
public class ResourceController {
    @Autowired
    private IResourceService rs;
    @Autowired
    private IAdminRoleService irs;


    //展示主页面中左侧菜单
    @GetMapping("/showUserMenu")
    public ResultEntity<List<Resource>> showUserMenu(HttpSession session){
        //从session里获取到用户对象
        Admin user = (Admin) session.getAttribute("user");
        int uId=user.getId();
        //查到它所对应的所有角色id
        List<Integer> integers = irs.selectAllRoleIdByUserId(uId);
        //根据所有角色id查对应的所有权限
        List<Resource> resources = rs.selectAllResourceByRoleIds(integers);
        return ResultEntity.ok(resources);
    }



    //获取权限树
    @GetMapping("/showAllResourceTree")
    public ResultEntity<List<Resource>> showAllResourceTree(){
        return ResultEntity.ok(rs.showAllResource());
    }

    //根据权限标记查找权限信息
    @GetMapping("/selectOne/{resourceId}")
    public ResultEntity<Resource> selectOne(@PathVariable int resourceId){
        Resource resource = rs.getById(resourceId);
        if(resource==null){
            return ResultEntity.error();
        }
        return ResultEntity.ok(resource);
    }
    //修改权限信息
    @PutMapping("/update")
    public ResultEntity updateResource(@RequestBody Resource resource){
        boolean b = rs.updateById(resource);
        if(b){
            return ResultEntity.ok();
        }
        return ResultEntity.error("修改失败");
    }
    //根据菜单标记查找该菜单下面的权限点
    @GetMapping("/selectChildrenByPid/{resourceId}")
    public ResultEntity<List<Resource>> selectChildren(@PathVariable int resourceId){
        List<Resource> list = rs.list();
        ResourceServiceImpl rri=new ResourceServiceImpl();
        List<Resource> resources = rri.selectAllChildren(resourceId,list);
        if(resources==null){
            return ResultEntity.error();
        }
        return ResultEntity.ok(resources);

    }
    //权限列表展示
    @GetMapping("/selectAll")
    public ResultEntity<List<Resource>> selectAll(){
        List<Resource> list = rs.list();
        if(list==null){
            return ResultEntity.error();
        }
        return ResultEntity.ok(list);
    }
}

